﻿using FineUI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Think.Data;
using Think.Permission;
using Think.Permission.Model;
using Think.Utils;
using Think.Web.App_Code;

namespace Think.Web.Admin.Permission
{
    public partial class AdminUser_Edit : AdminPage
    {
        AdminUser adminUser;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if ((adminUser = GetModelByID<AdminUser>()) != null)
                {
                    LoadData(this.Controls, adminUser);
                }
                Bind_rblRoles();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            bool isNew = false;
            if ((adminUser = GetModelByID<AdminUser>()) == null)
            {
                adminUser = new AdminUser();
                adminUser.RegTime = DateTime.Now;
                adminUser.LastLoginTime = DateTime.Now;

                if (Manage.IsExistName(txtLoginname.Text.Trim()))
                {
                    Alert.Show("用户名已存在");
                    return;
                }
                isNew = true;
            }
            LoadEntity(this.Controls, adminUser);

            if (!string.IsNullOrEmpty(txtPwd.Text.Trim()))
                adminUser.LoginPwd = Think.Utils.Encrypt.MD5(txtPwd.Text.Trim(), true);

            int adminID = 0;
            if (isNew)
            {
                adminID = TypeTo.ToInt(TRuntime.GetDB().Insert(adminUser));
            }
            else
            {
                adminID = adminUser.ID;
                TRuntime.GetDB().Update(adminUser);
            }

            if (adminID != 0)
            {
                string[] arrRoles = ddlRoles.SelectedValueArray;
                Manage.SetUserRoles(adminID, arrRoles);
            }

            ShowAlert("操作完成", true);
        }

        public void Bind_rblRoles()
        {
            ddlRoles.DataTextField = "Name";
            ddlRoles.DataValueField = "ID";
            ddlRoles.DataSource = Manage.GetAllRoles();
            ddlRoles.DataBind();

            if (adminUser != null)
            {
                List<AdminRoleMap> listRoles= Manage.GetUserRoles(ActionID);
                if (listRoles != null && listRoles.Count > 0)
                {
                    List<string> arr = new List<string>();
                    foreach (AdminRoleMap role in listRoles)
                    {
                        arr.Add(role.RoleID.ToString());
                    }
                    ddlRoles.SelectedValueArray = arr.ToArray();
                }
            }
        }
    }
}